"""
Web Routes

FastAPI routes for the AI Historical Simulation Platform web interface.
"""

import logging
from typing import Optional, Dict, Any

try:
    from fastapi import FastAPI, Request, HTTPException, WebSocket, WebSocketDisconnect
    from fastapi.responses import HTMLResponse, JSONResponse
    FASTAPI_AVAILABLE = True
except ImportError:
    FASTAPI_AVAILABLE = False

logger = logging.getLogger(__name__)


def setup_routes(app: FastAPI) -> None:
    """
    Setup all web routes for the application.
    
    Args:
        app: FastAPI application instance
    """
    if not FASTAPI_AVAILABLE:
        logger.error("FastAPI not available, cannot setup routes")
        return
    
    @app.get("/", response_class=HTMLResponse)
    async def chat_interface(request: Request):
        """Main chat interface."""
        return app.state.templates.TemplateResponse("chat.html", {"request": request})
    
    @app.get("/dashboard", response_class=HTMLResponse)
    async def dashboard(request: Request):
        """Administrative dashboard."""
        return app.state.templates.TemplateResponse("dashboard.html", {"request": request})
    
    @app.get("/scenarios", response_class=HTMLResponse)
    async def scenarios(request: Request):
        """Educational scenarios interface."""
        return app.state.templates.TemplateResponse("scenarios.html", {"request": request})
    
    @app.websocket("/ws")
    async def websocket_endpoint(websocket: WebSocket):
        """WebSocket endpoint for real-time communication."""
        await app.state.ws_manager.connect(websocket)
        try:
            while True:
                data = await websocket.receive_json()
                await app.state.ws_manager.handle_message(websocket, data)
        except WebSocketDisconnect:
            app.state.ws_manager.disconnect(websocket)
    
    @app.get("/api/figures")
    async def get_figures():
        """Get list of available historical figures."""
        try:
            figures = app.state.platform.figure_manager.list_available_figures()
            return {"figures": figures}
        except Exception as e:
            logger.error(f"Error getting figures: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.get("/api/metrics")
    async def get_metrics():
        """Get performance metrics."""
        try:
            metrics = app.state.platform.get_performance_metrics()
            return metrics
        except Exception as e:
            logger.error(f"Error getting metrics: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.get("/api/health")
    async def get_health():
        """Get system health status."""
        try:
            health = app.state.platform.get_system_health()
            return health
        except Exception as e:
            logger.error(f"Error getting health: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.post("/api/chat")
    async def chat_api(request: Dict[str, Any]):
        """REST API for chat interactions."""
        try:
            figure_name = request.get('figure')
            message = request.get('message')
            session_id = request.get('session_id', 'web_session')
            
            if not figure_name or not message:
                raise HTTPException(status_code=400, detail="Figure name and message are required")
            
            # Load figure if not already loaded
            figure = await app.state.platform.load_historical_figure(figure_name)
            
            # Generate response
            response = await app.state.platform.generate_response(
                figure.personality_id,
                message,
                session_id
            )
            
            return {
                "figure": figure_name,
                "response": response,
                "timestamp": app.state.platform.get_timestamp()
            }
            
        except Exception as e:
            logger.error(f"Error in chat API: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.get("/api/scenarios")
    async def get_scenarios():
        """Get educational scenarios."""
        try:
            # This would integrate with session controller
            scenarios = [
                {
                    "id": "demo_scenario",
                    "name": "Historical Leadership Discussion",
                    "description": "Explore leadership principles with historical figures",
                    "figures": ["Napoleon Bonaparte", "Julius Caesar"],
                    "difficulty": "intermediate"
                }
            ]
            return {"scenarios": scenarios}
        except Exception as e:
            logger.error(f"Error getting scenarios: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.post("/api/scenarios/{scenario_id}/start")
    async def start_scenario(scenario_id: str, request: Dict[str, Any]):
        """Start an educational scenario."""
        try:
            user_id = request.get('user_id', 'web_user')
            
            # This would integrate with session controller
            # For now, return a mock response
            return {
                "scenario_id": scenario_id,
                "session_id": f"scenario_{scenario_id}_{app.state.platform.get_timestamp()}",
                "status": "started"
            }
            
        except Exception as e:
            logger.error(f"Error starting scenario: {e}")
            raise HTTPException(status_code=500, detail=str(e))
    
    logger.info("Web routes setup complete")